/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-08-17 14:58:58
 * @LastEditTime: 2019-08-17 15:46:30
 * @LastEditors: Please set LastEditors
 */
var connect = require('connect')
var api = connect().use(users).use(pets).use(errorHandler)
var app = connect().use(hello).use('/api',api).use(errorPage).listen(3000)

function hello(req,res,next){
    console.log(req.url)
    if(req.url.match(/^\/hello/)){
        res.end('hello wor;d')
    }else{
        next()
    }
}


var db = {
    users : [
        {name:'t'},
        {name:'l'},
        {name:'j'},
    ]
}

function users(req,res,next){
    var match = req.url.match(/^\/user\/(.+)/)
    if(match){
        var user = db.users[match[1]]
        if(user){
            res.setHeader('Content-Type','application/json')
            res.end(JSON.stringify(user))
        }else{
            var err = new Error('User is not found')
            err.notFound = true
            next(err)
        }
    }else{
        next()
    }
}

function pets(req,res,next){
    if(req.url.match(/^\/pet\/(.+)/)){
        foo()
    }else{
        next()
    }
}


function errorHandler(err,req,res,next){
    // console.error(err.stack)
    res.setHeader('Content-Type','application/json')
    if(err.notFound){
        res.statusCode = 404
        res.end(JSON.stringify({error:err.message}))
    }else{
        res.statusCode = 500
        res.end(JSON.stringify({error:'Internet Server Error'}))
    }
}

function errorPage(err,req,res,next){
    res.end('系统错误')
}